<template>
	<Loading v-if="countdown <= 60 && countdown > 0"></Loading>

	<view class="container" v-else-if="countdown === 0">
		<scroll-view class="category-list" scroll-y>
			<view v-for="(category, index) in classOptions" :key="category.id"
				:class="['category-item', isleftCurrent === category.id ? 'active' : '']"
				@click="selectCategory(index)">
				<view class="containers" style="width: 66px;" v-if="category.id === isleftCurrent">
					<img :src="category.img" style="margin-left: -12px;width: 66px;height: 56px;" alt="Image"
						class="image" />
				</view>
				<p class="text">{{ category.name }}</p>
			</view>
		</scroll-view>

		<scroll-view class="product-list" scroll-y @scroll="onScroll" :scroll-into-view="scrollTarget">
			<view v-for="(category, index) in classOptions" :key="category.id" :id="'category-' + category.id">
				<view class="category-header">{{ category.name }}</view>
				<view>
					<image style="height: 90px;
    width: 93%;
    margin: 0 12px;"
						src="https://files.superbed.cn/proxy/7468686c6f2633336b776c74736873327f7872327e7f797e736f327f737133282429282c252e2f78782928292a2879242c2425292c292b7d2f7879257f242e782c2924287a797e32766c7b">
					</image>
				</view>
				<view v-for="product in getProductsByCategory(category.id)" :key="product.id"
					:ref="'product-'+product.id" class="pro-item">
					<image :src="product.image" class="product-image" :id="`image-${product.id}`" />
					<div class="product-content">
						<div>
							<div class="title">{{ product.name }}</div>
							<div class="content" style="margin-top: 32px;">¥{{ product.price }}</div>
						</div>
						<div class="bottom">
							<div class="bottom-right">
								<template v-if="product.number > 0">
									<div class="down" @click="handleDown(product)">-</div>
									<div class="number">{{ product.number }}</div>
								</template>
								<div class="up" @click="addToCart(product, $event)">+</div>
							</div>
						</div>
					</div>
				</view>
			</view>
		</scroll-view>


		<view v-if="animating" :style="animationStyle" class="bezier-animation">
			<image :src="products[current - 1].image" class="move-image" />
		</view>
		<div class="shopping-lines" v-if="allPrice">
			<view id="cart-icon" class="cart" ref="cart">

				<div class="image-container">
					<img src="https://doc.firstui.cn/img/img_logo.png" class="cart-image" />
					<fui-badge :value="numProcuct" background="#eee" color="#333" :absolute="true" :top="'-8rpx'"
						:right="'-18rpx'" class="badge">
					</fui-badge>
				</div>




			</view>
			<span v-if="allPrice" class="all-price"><span class="all-price-text">¥{{ allPrice }}</span></span>
			<!-- <span class="tips" v-else>未选购商品</span> -->
			<div :class="[allPrice ? 'can-buy' : '', 'buy-icon']">去结算</div>
		</div>
		<div class="shopping-line" v-else>
			<view id="cart-icon" class="cart" ref="cart">
				<image src="https://doc.firstui.cn/img/img_logo.png" class="cart-image" />
			</view>
			<!-- <span v-if="allPrice" class="all-price">¥<span class="all-price-text">{{ allPrice }}</span></span> -->
			<!-- 	<span class="tips">未选购商品</span>
			<div :class="[allPrice ? 'can-buy' : '', 'buy-icon']">去结算</div> -->
		</div>

	</view>
</template>

<script>
	import {
		url
	} from '@/utils/request.js';
	import {
		ref,
		onMounted,
		computed,
		onUnmounted,
		toRaw
	} from 'vue';
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		Loading
	} from '../Loading/Loading.vue';

	export default {
		components: {
			Loading
		},
		computed: {
			combinedCartItems() {
				return [

				];
			}
		},
		data() {
			return {
				productItems: [],
				countdown: 2,
				numProcuct: 0,
				isleftCurrent: 1, // 默认选中第一个分类
				current: 1,
				allPrice: 0,
				productAll: [],
				products: [],
				classOptions: [{
						id: 1,
						name: '鸡肉汉堡',
						img: 'https://files.superbed.cn/proxy/7468686c6f2633336b776c74736873327f7872327e7f797e736f327f7371332a2d29252e292e7878282e7d2e242f28297d2c29782a2a28287e7e297f25797d2d297f797e7a2f7d32766c7b.png'
					},
					{
						id: 2,
						name: '牛肉卷',
						img: 'https://files.superbed.cn/proxy/7468686c6f2633336b776c74736873327f7872327e7f797e736f327f737133242d2c7d2d2578247e7f2f797e2d2f297a7d2b7e292b78287e2a2d797d24782f7a782d7a28282e2932766c7b.png'
					},

					{
						id: 4,
						name: '套餐',
						img: 'https://files.superbed.cn/proxy/7468686c6f2633336b776c74736873327f7872327e7f797e736f327f7371332b2d7f7a2f7e7f2b257a2f787a24787f2c7f29782a7a7a7978782d2d2b2e247e282b2d2c2e242b2532766c7b.png'
					}
				],
				animating: false,
				animatingProduct: {},
				animationStyle: '',
				scrollTarget: 'category', // 默认滚动到第一个分类
			};
		},
		onLoad() {
			let interval = setInterval(() => {
				this.countdown--;
				if (this.countdown === 0) {
					clearInterval(interval);
				}
			}, 1000);
			uni.request({
				url: url + '/single/selectAll',
				method: 'get',
				success: (Res) => {
					console.log(Res.data.data)
					this.productItems = Res.data.data
					if (Res.data.data) {
						let nums = 0; 
						
						
						const categoryMap = {
						    '鸡肉汉堡': 1,
						    '牛肉卷': 2,
						    '套餐': 4
						};
						
						this.productItems.forEach(items => {
						
							let newproduct = {
								id: ++nums, 
								name: items.singleName || '',
								image: items.singleImg || '', 
								content: items.singleContain || '', 
								price: items.singlePrice || 0, 
								number: 0,
								categoryId: categoryMap[items.singlecategory] || null 
							};
						
							this.products.push(newproduct); 
							console.log(newproduct.categoryId,newproduct.name,"你好吧");
						});


						console.log(this.products.categoryId, "你好");
					}
				}
			});
		},
		methods: {
			handleDown(product) {
				this.numProcuct = this.numProcuct - 1;
				if (product.number > 0) {
					product.number--;
					this.allPrice -= product.price;
				}
			},
			addToCart(product, event) {
				this.numProcuct = this.numProcuct + 1;
				product.number = product.number + 1
				this.allPrice = this.allPrice + product.price
				setTimeout(() => {
					this.$nextTick(() => {
						const query = uni.createSelectorQuery().in(this);
						console.log(`Attempting to select: #image-${product.id}`);

						// Query the product image position
						query.select(`#image-${product.id}`).boundingClientRect();
						query.exec((res) => {
							const productRect = res[0];
							if (!productRect) {
								console.error(`Element #image-${product.id} not found.`);
								return;
							}

							// Start the animation with the product's position
							let startX = productRect.left;
							let startY = productRect.top;

							this.animatingProduct = product;
							this.animating = true;

							this.$nextTick(() => {
								const query2 = uni.createSelectorQuery().in(this);

								// Query the cart icon position
								query2.select('#cart-icon').boundingClientRect();
								query2.exec((res2) => {
									const cartRect = res2[0];
									if (!cartRect) {
										console.error('Cart icon not found.');
										return;
									}

									const endX = cartRect.left;
									const endY = cartRect.top + cartRect.height /
										2;

									const deltaX = endX - startX;
									const deltaY = endY - startY - 30;

									this.performAnimation(startX, startY, deltaX,
										deltaY);
								});
							});
						});
					});
				}, 100); // Delay before the query
			},

			performAnimation(startX, startY, deltaX, deltaY) {
				this.animationStyle = `
        top: ${startY}px;
        left: ${startX}px;
        transition: transform 0.5s;
        transform: translate3d(0, 0, 0);
      `;

				setTimeout(() => {
					this.animationStyle = `
          top: ${startY}px;
          left: ${startX}px;
          transition: transform 0.7s;
          transform: translate3d(${deltaX}px, ${deltaY}px, 0);
        `;
				}, 100);

				setTimeout(() => {
					this.animating = false;
					this.animationStyle = '';
					this.addProductToCart(this.animatingProduct);
				}, 800);
			},
			getProductsByCategory(categoryId) {
				return this.products.filter((product) => product.categoryId === categoryId);
			},
			selectCategory(index) {
				this.isleftCurrent = this.classOptions[index].id; // 更新当前套餐 ID
				this.scrollTarget = 'category-' + this.classOptions[index].id; // 生成目标 ID

				// 在 DOM 更新后进行滚动
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this); // 创建选择器查询
					query.select(`#${this.scrollTarget}`).boundingClientRect((rect) => {
						if (rect) {
							uni.pageScrollTo({
								scrollTop: rect.top + uni.getSystemInfoSync().windowHeight -
									100, // 调整为视口顶部可见
								duration: 100 // 滚动动画时长
							});
						} else {
							console.error('未找到目标元素：', this.scrollTarget);
						}
					}).exec();
				});
			},

			onScroll(event) {
				const scrollTop = event.detail.scrollTop;
				const categoryHeights = this.classOptions.map((category, index) => {
					return {
						id: category.id,
						top: index * this.getCategoryHeight(), // Height of each category
					};
				});

				// Determine which category the current scroll position is in
				for (let i = 0; i < categoryHeights.length; i++) {
					const pos = categoryHeights[i];
					const nextPos = i < categoryHeights.length - 1 ? categoryHeights[i + 1] : {
						top: Infinity
					};

					if (scrollTop >= pos.top && scrollTop < nextPos.top) {
						this.isleftCurrent = pos.id; // Update the selected category
						break;
					}
				}
			},
			getCategoryHeight() {
				return 200; // Adjust based on actual product count and height
			},
		},
	};
</script>

<style>
	.container {
		display: flex;
		height: 100vh;
	}

	.category-list {
		width: 20%;
		background-color: #f9f9f9;
		border-right: 1px solid #ddd;
		overflow-y: auto;
		max-height: 100vh;
	}

	.category-item {
		padding: 10px;
		cursor: pointer;
		text-align: center;
		color: #777777;
		background-color: #f8f8f8;
	}

	.active {
		background-color: #ffffff;
		color: black;
	}

	.product-list {
		background-color: white;
		width: 80%;
		overflow-y: auto;
		height: calc(100vh - 80px);
	}

	.category-header {
		font-size: 18px;
		/* font-weight: bold; */
		padding: 10px;
		/* background-color: #f0f0f0; */
	}

	.pro-item {
		display: flex;
		padding: 10px;
		border-bottom: 1px solid #ddd;
		margin-bottom: 5px;
	}

	.product-image {
		width: 80px;
		height: 80px;
		margin-right: 10px;
	}

	.product-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex: 1;
	}

	.title {
		/* margin-top: -24px; */
	}

	.bottom {
		display: flex;
		align-items: center;
	}

	.price {
		margin-right: 10px;
	}

	.bottom-right {
		display: flex;
		align-items: center;
	}

	.number {
		margin-top: 62px;
	}


	.up {
		cursor: pointer;
		color: #fef9f9;
		padding: 0 5px;
		background-color: red;
		border-radius: 100px;
		margin-top: 62px;
		margin-left: 10px;

	}

	.down {
		cursor: pointer;
		padding: 0 5px;
		/* background-color: #909090; */
		border-radius: 100px;
		margin-top: 62px;
		border: 1px solid #909090;
		margin-right: 10px;
	}

	.shopping-line {
		position: fixed;
		bottom: 14px;
		right: 20px;
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		border-radius: 21px;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		background: white;
		padding: 10px;
		box-shadow: 0 -1px 5px rgb(0 0 0 / 10%);
		opacity: 1;
		/* 初始状态完全可见 */
		/* 动画只在特定情况下触发，初始状态不需要 */
	}

	.shopping-lines {
		position: fixed;
		bottom: 14px;
		left: 20px;
		right: 20px;
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		border-radius: 21px;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		background: red;
		padding: 10px;
		box-shadow: 0 -1px 5px rgb(0 0 0 / 10%);
		opacity: 0;
		/* 初始状态不可见 */
		transform: translateY(20px);
		/* 初始向下偏移 */
		animation: fadeInUp 0.5s forwards;
		/* 添加淡入向上动画 */
	}

	/* 定义淡出动画 */
	@keyframes fadeOut {
		0% {
			opacity: 1;
			/* 完全可见 */
			transform: translateY(0);
			/* 初始位置 */
		}

		100% {
			opacity: 0;
			/* 淡出 */
			transform: translateY(-10px);
			/* 向上移动 */
		}
	}

	/* 定义淡入向上动画 */
	@keyframes fadeInUp {
		0% {
			opacity: 0;
			/* 初始不可见 */
			transform: translateY(20px);
			/* 从下方移动 */
		}

		100% {
			opacity: 1;
			/* 最终完全可见 */
			transform: translateY(0);
			/* 移动到原位置 */
		}
	}


	.cart {
		margin-right: auto;
	}

	.image-container {
		position: relative;
		/* Enable positioning for child elements */
		display: inline-block;
		/* Allows the container to shrink to fit the image */
	}

	.cart-image {
		width: 36px;
		/* Set the width of the image */
		height: 36px;
		/* Set the height of the image */
	}

	.badge {
		position: absolute;
		/* Position the badge absolutely */
		top: 0;
		/* Align it to the top */
		right: 0;
		/* Align it to the right */
		transform: translate(50%, -50%);
		/* Adjust position to center the badge over the corner */
		z-index: 1;
		/* Make sure the badge appears above the image */
	}

	.all-price {
		margin-left: -150px;
	}

	.all-price-text {
		font-size: 22px;
		color: white;
		/* font-family: '宋体'; */
		font-weight: bold;
	}

	.tips {
		margin-left: 10px;
		color: #999;
	}

	.buy-icon {
		margin-left: auto;
		font-size: 22px;
		margin-right: 10px;
		/* padding: 10px; */
		/* background-color: #007aff; */
		color: white;
		border-radius: 5px;
		cursor: pointer;
	}

	.bezier-animation {
		position: fixed;
		z-index: 1000;
	}

	.move-image {
		width: 50px;
		height: 50px;
	}
</style>